var startX = 0,startY = 0;
var canvasLayer, canvasContainer;
$(function() {
	$("#picture-upload").click(function(e){
		$("#upload-dialog").lightbox_me({
			centered:true,
			onLoad: function() {}
	    });
		e.preventDefault();
	});
	
	$("#background-picker").ColorPicker({
			onSubmit: function (hsb, hex, rgb, el) {
				changeBg(hex);
				$(el).ColorPickerHide();
			}
	});
	
	$('#picture-trigger').click(function(e) {
	    $('#pictureList').lightbox_me({
	        centered: true, 
	        onLoad: function() { 
		        	$.getJSON('services/manager/pictures', function(data) {
		        		  $.each(data, function(key, val) {
		        			  $.each(val, function(innerKey, innerValue) {
		        				$("<img/>").attr("src", innerValue.url)
		        					.appendTo("#images").css("width", "120px")
		        					.css("height", "120px")
		        					.on('click',function(event){
		        						draw($(this))
		        					});
		        			  });
		        		  });
	        		});
	        	}
	        });
	    e.preventDefault();
	});
	
	$('#picture-save').click(function(e) {
		var picture = $("div#container > div > canvas")[0].toDataURL("images/png");
		$.post('services/manager/scrapPage',{'image':picture},
			function(file){               
	        	//Callback code
	        	alert("done");
	    	}
		);
	});
	
	$('#pictureUploader').fileupload({
        dataType: 'multipart/form-data',
        done: function (e, data) {
        	/* alert(data);
        	alert(e); */
            /*$.each(data.result, function (index, file) {
                $('<p/>').text(file.name).appendTo(document.body);
            }); */
        	$("#upload-dialog").css("display", "none");
        }
    });
	
	$("#upload-dialog").css("display", "none");
	$("#color-dialog").css("display", "none");
});
window.onload = function() {
	var stage = new Kinetic.Stage({
		container : "container",
		width : 450,
		height : 420
	});

	var layer = new Kinetic.Layer();
	canvasLayer = layer;
	stage.add(layer);
	//backgroundLayer = new Kinetic.Layer();
	stage.setOpacity(1);
	//stage.add(backgroundLayer);
	canvasContainer = stage;
}
function draw(image){
    var img = image.get(0);
    var baby = new Kinetic.Image({
		x : startX,
		y : startY,
		image : img,
		width : 100,
		height : 100,
		draggable : true
	});
    canvasLayer.add(baby);
    canvasLayer.draw();
}

function changeBg(color){
	/*
	backgroundLayer.get
	var rect = new Kinetic.Rect({
        x: 239,
        y: 75,
        width: 100,
        height: 50,
        fill: 'green',
        stroke: 'black',
        strokeWidth: 4
      });
      */
	$("#container canvas").css("background-color","#"+color);
}

